package base.loader {
	import flash.display.Sprite;
	import base.loader.LoadContentQueue;
	import base.loader.show.LoaderProgress;
	import base.loader.show.LoaderShowSimple;
	import com.greensock.TweenNano;
	import flash.display.DisplayObject;
	
    public class LibraryLoader extends Sprite {
		
		private static const COUNT_FRAMES_SHOW_HIDE: uint = 10;
		
		private var loaderShow: LoaderShowSimple;
		protected var loadContentQueue: LoadContentQueue;
		private var arrIndSwfLib: Array;
		protected var isAllLibrariesLoaded: Boolean;
		public var arrSwfLib: Array;
		
		function LibraryLoader(arrFilenameSwfLib: Array): void {
			this.createLoaderShow();
			this.prepareLoadContentQueue(arrFilenameSwfLib);
		}
		
		protected function createProgress(): LoaderProgress {
			return null;
		}
		
		private function createLoaderShow(): void {
			this.loaderShow = new LoaderShowSimple(this.createProgress());
			this.addChild(this.loaderShow);
			TweenNano.from(this.loaderShow, LibraryLoader.COUNT_FRAMES_SHOW_HIDE, {alpha: 0, useFrames: true, onComplete: this.startLoading});
		}
		
		private function prepareLoadContentQueue(arrFilenameSwfLib: Array): void {
			this.loadContentQueue = new LoadContentQueue(this.onContentLoadCompleteHandler, this, this.loaderShow);
			this.loadContent(arrFilenameSwfLib);
		}
		
		protected function loadContent(arrFilenameSwfLib: Array): void {
			this.arrIndSwfLib = [];
			for (var i:uint = 0; i < arrFilenameSwfLib.length; i++) {
				this.arrIndSwfLib.push(this.loadContentQueue.addToLoadQueue(String(arrFilenameSwfLib[i])));
			}
		}
		
		private function startLoading(): void {
			this.loadContentQueue.startLoading();
		}
		
		protected function onContentLoadCompleteHandler(arrContent: Array): void {
			this.isAllLibrariesLoaded = true;
			this.arrSwfLib = new Array(this.arrIndSwfLib.length);
			for (var i:uint = 0; i < this.arrIndSwfLib.length; i++) {
				var objSwfLib: Object = arrContent[this.arrIndSwfLib[i]];
				if (objSwfLib.isLoaded) {
					if (objSwfLib.type == LoadContentQueue.SWF) {
						this.arrSwfLib[i] = objSwfLib.content;
						Library.addSwf(DisplayObject(objSwfLib.content));
					}
				} else this.isAllLibrariesLoaded = false;
			}
			this.hideLoaderShow();
		}
		
		private function hideLoaderShow(): void {
			TweenNano.to(this.loaderShow, LibraryLoader.COUNT_FRAMES_SHOW_HIDE, {alpha: 0, useFrames: true, onComplete: this.onHideLoaderShow});
		}
		
		protected function onHideLoaderShow(): void {
			if (this.isAllLibrariesLoaded) this.dispatchEvent(new LibraryLoaderEvent(LibraryLoaderEvent.LIBRARIES_LOAD_SUCCESS));
			else this.dispatchEvent(new LibraryLoaderEvent(LibraryLoaderEvent.LIBRARIES_LOAD_ERROR));
		}
		
	}
}
